package com.bjpowernode.controller;

import com.bjpowernode.entity.TPermission;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.query.UserQuery;
import com.bjpowernode.result.Result;
import com.bjpowernode.service.PermissionService;
import com.bjpowernode.service.UserService;
import com.bjpowernode.util.LoginInfoUtil;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 用户Controller
 */
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    @GetMapping("api/login/user")
    public Result getUser() {
        //获取当前的登录用户信息
        TUser currentLoginUser = LoginInfoUtil.getCurrentLoginUser();

        //查询当前登录用户对应的权限
        List<TPermission> tMenuPermissionList = permissionService.getMenuPermissionList(currentLoginUser.getId());

        //将权限信息放入用户对象中
        currentLoginUser.setTMenuPermissionList(tMenuPermissionList);

        return Result.OK(currentLoginUser);
    }


    /**
     * 分页查询用户信息
     */
    @GetMapping("api/users")
    public Result getUsers(Integer current) {
        //给前端返回分页的数据
        PageInfo<TUser> pageInfo = userService.getUserByPage(current);

        return Result.OK(pageInfo);
    }

    /**
     * 根据用户主键查询用户信息
     */
    @GetMapping("api/user/{id}")
    public Result getUserById(@PathVariable Integer id) {
        TUser user = userService.getUserById(id);

        return Result.OK(user);
    }


    /**
     * 用户添加
     */
    @PostMapping("/api/user")
    public Result addUser(@Valid UserQuery userQuery) {
        int count = userService.saveUser(userQuery);
        return count == 1 ? Result.OK() : Result.FAIL();
    }


    /**
     * 用户修改
     */
    @PutMapping("/api/user")
    public Result editUser(UserQuery userQuery){
        int count = userService.updateUser(userQuery);
        return count == 1 ? Result.OK() : Result.FAIL();
    }

    /**
     * 用户删除
     */
    @DeleteMapping("/api/user/{id}")
    public Result delUser(@PathVariable Integer id){
        int count = userService.deleteUser(id);
        return count == 1 ? Result.OK() : Result.FAIL();
    }

    /**
     * 用户批量删除
     */
    @DeleteMapping("/api/user")
    public Result delUsers(String ids){
       //将字符串转出数组
        List<String> idList = Arrays.asList(ids.split(","));

        int num = userService.batchDeleteUser(idList);

        return num == idList.size() ? Result.OK() : Result.FAIL();
    }


    /**
     * 查询所有负责人  用户
     */
    @GetMapping("/api/owners")
    public Result getOwners() {
        List<TUser> users = userService.getOwners();
        return Result.OK(users);
    }
}
